#-*-coding:utf-8-*-

from BeautifulSoup import BeautifulSoup
import re, urllib2

class CourseParser:

    def __init__(self, html):
        self.html = html
        self.now_day = 0
        self.now_start_time = self.now_end_time = 0
        self.p = re.compile("\d-\d")
        self.p2 = re.compile("(?:<br />)?(\w+)")
        self.days = { u'一': 1, u'二': 2, u'三': 3, u'四': 4, u'五': 5, u'六': 6, u'七': 7, u'日': 7 }
        self.result = []

    def parse(self):
        soup = BeautifulSoup(self.html)
        table = soup.find(id="report1")
        trs = table.findAll("tr")[2:]

        for tr in trs:
            tds = [
                "".join([unicode(s) for s in td.contents]) 
                for td in tr.findAll("td")
            ]
            course = self.getCourseInfo(tds)
            self.result.append(course)
        return self.result

    def getCourseInfo(self, tds):
        first_cell = tds[0]
        if first_cell.startswith(u'星期'):
            self.now_day = self.days[first_cell[-1]]
            return self.getCourseInfo(tds[1:])
        elif re.match(self.p, first_cell):
            if first_cell:
                self.now_start_time, self.now_end_time = [int(t) for t in first_cell.split('-')]
            else:
                self.now_start_time = self.now_end_time = None
            return self.getCourseInfo(tds[1:])
        elif not tds[0] and not tds[1]:
            return self.getCourseInfo(tds[2:]);
        else:
            if tds[1] == '-' and not tds[2]:
                course = {
                    'weekday': None,
                    'start_time': None,
                    'end_time': None,
                    'name': tds[0].replace("<br />", ""),
                    'from_week': None,
                    'to_week'  : None,
                    'building': None,
                    'room': None,
                    'teacher': tds[4]
                  }
            else:
                room_info = re.findall(self.p2, tds[2])
                from_to = tds[1].split('-') if tds[1].strip() else [None, None]
                course = {
                    'weekday': self.now_day,
                    'start_time': self.now_start_time,
                    'end_time': self.now_end_time,
                    'name': tds[0].replace("<br />", ""),
                    'from_week': from_to[0],
                    'to_week'  : from_to[1],
                    'building': re.sub(self.p2, "", tds[2]) or None,
                    'room': room_info[0] if room_info else None,
                    'teacher': tds[4]
                }
            return course


if __name__ == "__main__":
    fp = open("kebiao20111_2010/U201015426.html")
    content = fp.read()
    fp.close()
    
    parser = CourseParser(content)
    courses =  parser.parse()

    for course in courses:
        for key in course:
            print key, course[key]
        print ""
